<script setup lang="ts">
import {
  getProductTypePage,
  getProductForm,
  addUser,
  updateUser,
  deleteUsers,
} from "@/api/productType/index";

import { UserPageVO, UserForm, UserQuery } from "@/api/productType/types";

defineOptions({
  name: "product",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const UserFormRef = ref(ElForm);
const menuRef = ref(ElTree);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<UserQuery>({
  pageindex: 1,
  pagesize: 10,
});

const roleList = ref<UserPageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

/**
 * 产品表单返回值
 */
const formData = reactive<UserForm>({
  productTypeId: "",
  productTypeName: "",
  pid: undefined,
  productTypeDesc: "",
  child: undefined,
});

const rules = reactive({
  productName: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
  productId: [{ required: true, message: "请输入产品编码", trigger: "blur" }],
  price: [{ required: true, message: "请选择价格", trigger: "blur" }],
  weight: [{ required: true, message: "请选择重量", trigger: "blur" }],
});

const menuDialogVisible = ref(false);

const menuList = ref<OptionType[]>([]);

interface CheckedRole {
  id?: number;
  name?: string;
}
let checkedRole: CheckedRole = reactive({});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getProductTypePage(queryParams)
    .then(({ data }) => {
      roleList.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageindex = 1;
  handleQuery();
}

/** 行checkbox 选中事件 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/** 打开角色表单弹窗 */
function openDialog(productId?: string) {
  dialog.visible = true;
  if (productId) {
    dialog.title = "修改角色";
    getProductForm(productId).then(({ data }) => {
      Object.assign(formData, data);
      console.log(data);
    });
  } else {
    dialog.title = "新增角色";
  }
}

/** 角色保存提交 */
function handleSubmit() {
  UserFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.productTypeId;
      if (roleId) {
        updateUser(roleId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addUser(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  UserFormRef.value.resetFields();
  UserFormRef.value.clearValidate();

  // formData.id = undefined;
  // formData.sort = 1;
  // formData.status = 1;
}

/** 删除角色 */
function handleDelete(productId?: string) {
  const roleIds = [productId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteUsers(roleIds)
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

/** 打开分配菜单弹窗 */
// function openMenuDialog(row: UserPageVO) {
//   const roleId = row.productId;
//   if (roleId) {
//     checkedRole = {
//       id: roleId,
//       name: row.name,
//     };
//     menuDialogVisible.value = true;
//     loading.value = true;

//     // 获取所有的菜单
//     getMenuOptions().then((response) => {
//       menuList.value = response.data;
//       // 回显角色已拥有的菜单
//       getRoleMenuIds(roleId)
//         .then(({ data }) => {
//           const checkedMenuIds = data;
//           checkedMenuIds.forEach((menuId) =>
//             menuRef.value.setChecked(menuId, true, false)
//           );
//         })
//         .finally(() => {
//           loading.value = false;
//         });
//     });
//   }
// }

/** 角色分配菜单保存提交 */
// function handleRoleMenuSubmit() {
//   const roleId = checkedRole.id;
//   if (roleId) {
//     const checkedMenuIds: number[] = menuRef.value
//       .getCheckedNodes(false, true)
//       .map((node: any) => node.value);

//     loading.value = true;
//     updateUserMenus(roleId, checkedMenuIds)
//       .then(() => {
//         ElMessage.success("分配权限成功");
//         menuDialogVisible.value = false;
//         resetQuery();
//       })
//       .finally(() => {
//         loading.value = false;
//       });
//   }
// }

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 删除新增，列表 -->
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success"
          ><i-ep-plus @click="openDialog('')" />新增</el-button
        >
        <el-button
          type="danger"
          @click="handleDelete()"
          :disabled="ids.length === 0"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <!-- 列表 -->
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="roleList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="产品分类编号" prop="productTypeId" />
        <el-table-column label="产品分类名称" prop="productTypeName" />
        <el-table-column label="上级类别" prop="pid" />
        <el-table-column label="备注" prop="productTypeDesc" />
        <el-table-column label="创建时间" prop="addDate" />

        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row.productId)"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleDelete(scope.row.productId)"
            >
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageindex"
        v-model:limit="queryParams.pagesize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        ref="UserFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="分类编号" prop="productTypeId">
              <el-input
                v-model="formData.productTypeId"
                placeholder="请输入分类编号"
              />
            </el-form-item>
            <el-form-item label="分类名称" prop="productTypeName">
              <el-input
                v-model="formData.productTypeName"
                placeholder="请输入分类名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="上级类别" prop="pid">
              <el-input v-model="formData.pid" placeholder="上级类别" />
            </el-form-item>
            <el-form-item label="备注" prop="productTypeDesc">
              <el-input
                v-model="formData.productTypeDesc"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配菜单弹窗  -->
    <el-dialog
      v-model="menuDialogVisible"
      :title="'【' + checkedRole.name + '】权限分配'"
      width="800px"
    >
      <el-scrollbar v-loading="loading" max-height="600px">
        <el-tree
          ref="menuRef"
          node-key="value"
          show-checkbox
          :data="menuList"
          :default-expand-all="true"
        >
          <template #default="{ data }">
            {{ data.label }}
          </template>
        </el-tree>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="handleRoleMenuSubmit"
            >确 定</el-button
          > -->
          <el-button @click="menuDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<!-- function defineOptions(arg0: { name: string; inheritAttrs: boolean; }) { throw
new Error("Function not implemented."); } -->
